import React, { Component } from "react";
import { connect } from 'react-redux'
import Remind from "components/template/remind/remind";
import { Form, Switch, Checkbox, Input, Row, Col, Select, InputNumber, message, Button, Spin, Radio } from 'antd'
import { messages } from "share/common";
import WrapFormItem from "components/wrap-form-item";
import Priority from "components/template/priority";
import CompactInput from 'components/compact-input'
import beepTimerService from "../beep-timer.service";
import Chooser from 'components/chooser';

const { Option } = Select;

@Form.create()
@connect(mapStateToProps)
class RefundContent extends Component {

  state = {
    priority: null,
    invoiceOption: [],
    loanOption: [],
    saveLoading: false,
    loading: false
  };

  targetOptions = [
    { label: messages('common.applicant')/*申请人*/, value: 'CREATED_BY' },
    { label: messages('basic-13.key116')/*收款人（仅限员工）*/, value: 'PAYEE' },
    { label: messages('basic-13.key117')/*财务*/, value: 'FINANCE' },
    { label: messages('basic-13.key168')/*借款人部门经理*/, value: 'PAYEE_MANAGER' },
    { label: messages('basic-13.key169')/*借款人直属领导*/, value: 'PAYEE_LEADER' },
    { label: messages('basic-13.key170')/*申请人部门经理*/, value: 'CREATED_BY_MANAGER' },
    { label: messages('basic-13.key171')/*申请人直属领导*/, value: 'CREATED_BY_LEADER' }
  ];

  componentWillMount() {
    const { record, info } = this.props.params, { company } = this.props;
    let priority = info.id ? {
      levelOrgName: record.levelOrgName,
      levelOrgId: record.levelOrgId,
      levelCode: record.levelCode,
      distribution: record.isGlobal ? null : {
        companies: record.distribution ? record.distribution.map(item => { return { name: item.levelOrgName, id: item.levelOrgId } }) : []
      }
    } : {
      levelOrgName: company.setOfBooksName,
      levelOrgId: company.setOfBooksId,
      levelCode: 'SET_OF_BOOK',
      distribution: {
        companies: [{ name: company.name, id: company.id }]
      }
    };
    this.setState({ priority }, this.handleOption);
  };

  componentDidMount = () => {
    this.getConditionRule();
  };

  getConditionRule = () => {
    const { info } = this.props.params;
    this.setState({ loading: true });
    info.id && beepTimerService.getHonestList(info.id).then(res => {
      this.props.form.setFieldsValue({
        conditionId: res.data.id ? [{ id: res.data.id, ruleCondition: res.data.ruleCondition }] : []
      });
      this.setState({ loading: false });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ loading: false });
    })
  };

  handleOption = () => {
    const { priority } = this.state, { company } = this.props;
    if (priority) {
      this.setState({ loading: true });
      Promise.all([
        priority.distribution && priority.distribution.companies && priority.distribution.companies.length ?
          beepTimerService.getAllInvoiceType(priority.distribution.companies[0].id) :
          (priority.levelCode === 'COMPANY'
            ? beepTimerService.getAllInvoiceType(priority.levelOrgId)
            : beepTimerService.getSetOfBookLoanType(priority.levelOrgId)
          ),
        beepTimerService.getAllLoanType(company.setOfBooksId)
      ]).then(res => {
        let invoiceOption = [];
        let loanOption = [];
        res[0].data.map(item => {
          let temp = {
            label: item.formName,
            value: item.formOID
          };
          invoiceOption.push(temp);
        });
        res[1].data.map(item => {
          let temp = {
            label: item.description,
            value: item.id
          };
          loanOption.push(temp);
        });
        this.setState({
          invoiceOption,
          loanOption,
          loading: false
        })
      }).catch(() => {
        message.error(messages('basic-13.key129')/*系统异常*/);
        this.setState({ loading: false })
      });
    }
  };

  handlePriority = value => {
    this.props.form.setFieldsValue({
      warpObject: { fitObj: 'formOids', fitIds: [] },
      conditionId: []
    });
    this.setState({ priority: value }, this.handleOption);
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { priority } = this.state, { info } = this.props.params, { close } = this.props;
        if (!priority || (priority.distribution && priority.distribution.companies.length === 0)) {
          message.error(messages('basic-13.key225')/*请分配权限*/);
          return -1;
        }
        if (!value.warpTime.differenceDate) {
          message.error(messages('basic-13.key226')/*请输入触发时间*/);
          return -1;
        }
        this.setState({ saveLoading: true });
        this.warpRemind.saveValue().then(id => {
          let params = {
            enabledFlag: value.enabledFlag,
            code: 'RepaymentNoticeTask',
            hour: Number(this.warpRemind.getValue().remindWarpValue.remindTimes[0].split(':')[0])
          };
          params.params = Object.assign({
            title: value.title,
            content: value.content,
            repaymentRemindPersonTypes: value.repaymentRemindPersonTypes,
            regulationId: id,
            needBillContent: value.needBillContent
          }, priority, value.warpTime);
          let distributionList = params.params.distribution;
          delete params.params.distribution;
          params.params.isGlobal = !distributionList;
          distributionList && (params.params.distribution = distributionList.companies.map(item => ({
            levelCode: 'COMPANY',
            levelOrgId: item.id,
            levelOrgName: item.name
          })));
          params.params[value.warpObject.fitObj === 'formOids' ? 'formOids' : 'loanTypeIds'] = value.warpObject.fitIds;
          params.params = JSON.stringify(params.params);
          info.id && (params.id = info.id);
          beepTimerService.newBeepTimer(params).then(res => {
            beepTimerService.saveHonestInfo({
              taskId: params.id || res.data.rows.id,
              conditionId: ((value.conditionId || [])[0] || {}).id
            }).then(() => {
              this.setState({ saveLoading: false });
              close(true);
            })
          })
        }).catch(e => {
          this.setState({ saveLoading: false });
          e.response && message.error(e.response.data.message);
        });
      }
    })
  };

  options = [
    { label: messages('basic-13.key8')/*启用temp*/, value: true },
    { label: messages('basic-13.key227')/*不启用*/, value: false }
  ];

  render() {
    const { record, info } = this.props.params,
      { priority, invoiceOption, loanOption, saveLoading, loading } = this.state,
      { close } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    return (
      <div>
        <Spin spinning={loading}>
          <Form className={'new-form'}>
            <Form.Item
              label={messages('common.column.status')/*状态*/}
              {...formItemLayout}
            >
              {getFieldDecorator("enabledFlag", {
                rules: [{ required: true }],
                valuePropName: "checked",
                initialValue: info.hasOwnProperty('enabledFlag') ? info.enabledFlag : true
              })(
                <Switch/>
              )}
            </Form.Item>
            <Priority
              top='SET_OF_BOOK'
              disabled={info.hasOwnProperty('id')}
              disabledTop
              onChange={this.handlePriority}
              formItemLayout={formItemLayout}
              defaultValue={priority}
              single={false}
            />
            <h3 className='sub-title'>{messages('basic-13.key12')/*提醒对象*/}</h3>
            <Form.Item
              label={messages('basic-13.key12')/*提醒对象*/}
              {...formItemLayout}
            >
              {getFieldDecorator("repaymentRemindPersonTypes", {
                rules: [{ required: true }],
                initialValue: record.repaymentRemindPersonTypes || ['CREATED_BY']
              })(
                <Checkbox.Group options={this.targetOptions}/>
              )}
            </Form.Item>
            <h3 className='sub-title'>{messages('basic-13.key15')/*消息内容*/}</h3>
            <Form.Item
              label={messages('basic-13.key16')/*消息标题*/}
              {...formItemLayout}
            >
              {getFieldDecorator("title", {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key16')/*消息标题*/})/*{arg1} 不能为空*/
                }, {
                  max: 50,
                  message: messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/
                }],
                initialValue: record.title
              })(
                <Input placeholder={messages('basic-13.key228')/*借款还款提醒*/}/>
              )}
            </Form.Item>
            <Form.Item
              label={messages('basic-13.key17')/*消息正文*/}
              {...formItemLayout}
            >
              {getFieldDecorator('content', {
                rules: [{
                  required:true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key17')/*消息正文*/})/*{arg1} 不能为空*/
                }, {
                  max: 100,
                  message: messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/
                }],
                initialValue: record.content
              })(
                <Input.TextArea placeholder={messages('basic-13.key229')/*请及时还款*/}/>
              )}
            </Form.Item>
            <Form.Item
              label={messages('basic-13.key230')/*单据详情*/}
              {...formItemLayout}
            >
              {getFieldDecorator('needBillContent', {
                rules: [{
                  required:true
                }],
                initialValue: record.hasOwnProperty('needBillContent') ? record.needBillContent : true
              })(
                <Radio.Group options={this.options}/>
              )}
            </Form.Item>
            <h3 className='sub-title'>{messages('basic-13.key18')/*消息触发*/}</h3>
            <Form.Item
              label={messages('basic-13.key231')/*触发对象*/}
              {...formItemLayout}
            >
              {getFieldDecorator('warpObject', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key231')/*触发对象*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.hasOwnProperty('id') ? {
                  fitObj: record.formOids ? 'formOids' : 'loanTypeIds',
                  fitIds: record.formOids ? record.formOids : record.loanTypeIds
                } : { fitObj: 'formOids', fitIds: [] }
              })(
                <WrapFormItem>
                  {(onChange, value) => (
                    <CompactInput>
                      <Select
                        value={value.fitObj}
                        onChange={value => onChange({ fitObj: value, fitIds: [] })}
                      >
                        <Option key={'formOids'}>{messages('basic-13.key60')/*单据类型*/}</Option>
                        <Option key={'loanTypeIds'}>{messages('basic-13.key162')/*借款类型*/}</Option>
                      </Select>
                      <Select
                        mode='multiple'
                        placeholder={messages('basic-13.key232')/*默认全部，请选择*/}
                        value={value.fitIds}
                        onChange={value => onChange({ fitIds: value })}
                      >
                        {(value.fitObj === 'formOids' ? invoiceOption : loanOption).map(item => <Option key={item.value}>{item.label}</Option>)}
                      </Select>
                    </CompactInput>
                  )}
                </WrapFormItem>
              )}
            </Form.Item>
            <Remind
              id={record.regulationId}
              onRef={ref => this.warpRemind = ref}
              hideType
            >
              <Form.Item
                label={messages('basic-13.key233')/*触发时间*/}
                {...formItemLayout}
              >
                {getFieldDecorator('warpTime', {
                  rules: [{
                    required: true,
                    message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key233')/*触发时间*/})/*{arg1} 不能为空*/
                  }],
                  initialValue: info.hasOwnProperty('id') ? {
                    repaymentRemindBaseDateType: record.repaymentRemindBaseDateType,
                    differenceDate: record.differenceDate
                  } : { repaymentRemindBaseDateType: 'BEFORE_PLANED_REPAYMENT_DATE' }
                })(
                  <WrapFormItem>
                    {(onChange, value) => (
                      <Row gutter={10}>
                        <Col span={12}>
                          <Select
                            placeholder={messages('common.select')/*请选择*/}
                            value={value.repaymentRemindBaseDateType}
                            onChange={value => onChange({ repaymentRemindBaseDateType: value })}
                          >
                            <Option key={'BEFORE_PLANED_REPAYMENT_DATE'}>{messages('basic-13.key135')/*预计还款日期前*/}</Option>
                            <Option key={'AFTER_PLANED_REPAYMENT_DATE'}>{messages('basic-13.key234')/*预计还款日期后*/}</Option>
                            <Option key={'AFTER_APPROVED_DATE'}>{messages('basic-13.key136')/*审批通过日期后*/}</Option>
                            <Option key={'AFTER_AUDIT_DATE'}>{messages('basic-13.key137')/*审核通过日期后*/}</Option>
                            <Option key={'AFTER_PAYMENT_DATE'}>{messages('basic-13.key235')/*付款日期后*/}</Option>
                          </Select>
                        </Col>
                        <Col span={4}>
                          <InputNumber
                            onChange={ value => onChange({ differenceDate: value }) }
                            step={1} min={1} precision={0} style={{width:'100%'}}
                            value={value.differenceDate}
                          />
                        </Col>
                        <Col span={8}>
                          {messages('basic-13.key236')/*天需要提醒员工*/}
                        </Col>
                      </Row>
                    )}
                  </WrapFormItem>
                )}
              </Form.Item>
            </Remind>
            <h3 className='sub-title'>{messages('basic-13.key237')/*附加控制*/}</h3>
            <Form.Item
              label={messages('basic-13.key238')/*触发信用规则*/}
              {...formItemLayout}
            >
              {getFieldDecorator('conditionId')(
                <Chooser
                  type={'beer-honest'}
                  showClear
                  valueKey="id"
                  single
                  labelKey="ruleCondition"
                  listExtraParams={
                    Object.assign({
                      taskConfigCode: 'RepaymentNoticeTask'
                    }, priority.distribution && priority.distribution.companies && priority.distribution.companies.length ? {
                      companyId: priority.distribution.companies[0].id
                    } : {
                      setOfBooksId: priority.levelOrgId
                    })
                  }
                />
              )}
            </Form.Item>
          </Form>
        </Spin>
        <div className='slide-footer'>
          <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default RefundContent
